package ils.web.lifecycle;

import ils.util.HibernateUtil;
import ils.util.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.AbstractApplicationContext;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

/**
 * Created with IntelliJ IDEA.
 * User: rejeevd
 * Date: 01/10/12
 * Time: 15:26
 * To change this template use File | Settings | File Templates.
 */
public class UndeployListener implements ServletContextListener
{
    private static final Logger logger = LoggerFactory.getLogger(UndeployListener.class);

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        logger.info("ILS deployed...");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        AbstractApplicationContext context = (AbstractApplicationContext)SpringUtil.getApplicationContext();
        context.destroy();
        logger.info("application context destroyed...");
        HibernateUtil.shutdown();
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements())
        {
            Driver driver = drivers.nextElement();
            try {
                DriverManager.deregisterDriver(driver);
            } catch (SQLException e) {
                logger.error("Some exception during unregistering database  drivers", e);
            }
        }
    }
}
